import axios from 'axios'
import cookie from 'js-cookie'
import { Message, MessageBox, TimeSelect } from 'element-ui'
// 创建axios实例
const service = axios.create({
  baseURL: 'http://localhost:8222', // api的base_url
  timeout: 20000 // 请求超时时间
})

service.interceptors.request.use(
  config=>{
    if(cookie.get('token')){
      config.headers['token'] = cookie.get('token');
    }
    return config;
  }
)

service.interceptors.response.use(
  response => {
    const res = response.data
    if (!res.success) {
      if(res.code==20001){
        Message({
          message: res.message,
          type: 'error',
          duration: 5 * 1000
        })
      }
      if(res.code==30000){
        Message({
          message: res.message,
          type: 'error',
          duration: 5 * 1000
        })
        setTimeout(()=>{window.location.href="/login"},2000)
      }

      console.log(`errorCode:${res.code},errorMsg:${res.message}`);
      return Promise.reject('error')
    } else {
      return response.data
    }
  },
  error => {
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
);
export default service